<template>
    <el-container style="width: 100%; height: 100%">
        <el-header>
            <!--              患者-->
            <div class="image-preview">
                <el-button type="primary" @click="prevPatient">上一位</el-button>

                <div class="image-count">
                    共 {{ patientsDir.length }} 位患者，当前患者：
                    <a-tag color="cyan" style="font-size: 1.4rem">{{ currentPatient?.name }}</a-tag>
                    第{{ currentPatientIndex + 1 }}位
                    <a-tag :color="diagnosisResult.length !== 0  ? 'green' : 'red'">
                        {{ diagnosisResult.length !== 0 ? '已标注' : '未标注' }}
                    </a-tag>
                </div>

                <el-button type="primary" @click="nextPatient">下一位</el-button>

                <el-button @click=" selectDirectory()">选择文件夹</el-button>

                <el-dialog
                        title="选择文件夹"
                        v-model="selectDirectoryDialog.visible"
                        @close="selectDirectoryDialog.close()"

                >
                    <el-table
                            ref="fileTable"
                            :data="selectDirectoryDialog.fileList"
                            v-loading="selectDirectoryDialog.loading"
                            border
                            style="width: 100%"
                            row-key="name"
                            highlight-current-row
                            @current-change="handleDirectoryClick"
                    >
                        <el-table-column type="index" width="50"/>
                        <el-table-column prop="name" label="文件夹名" min-width="200">
                            <template #default="scope">
                                <div class="file-item">
                                    <el-icon
                                            :size="18"
                                            :color="scope.row.type === 'directory' ? '#409EFF' : '#67C23A'"
                                    >
                                        <component :is="scope.row.type === 'directory' ? 'Folder' : 'Document'"/>
                                    </el-icon>
                                    <span class="file-name">{{ scope.row.name }}</span>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="type" label="类型" width="100">
                            <template #default="scope">
                                <el-tag :type="scope.row.type === 'directory' ? 'primary' : 'success'">
                                    {{ scope.row.type === 'directory' ? '文件夹' : '文件' }}
                                </el-tag>
                            </template>
                        </el-table-column>
                    </el-table>
                    <template #footer>
                        <div class="dialog-footer">
                            <el-button @click="selectDirectoryDialog.visible = false">取消</el-button>
                            <el-button type="primary" @click="handleDirectoryConfirm()">确定</el-button>
                        </div>
                    </template>
                </el-dialog>
            </div>
        </el-header>
        <!--        内容区-->
        <el-main style="overflow: hidden; padding: 0">
            <a-row :gutter="[16, 16]">
                <a-col :span="2">
                    <div style="height: 100%; padding-left: 6px">
                        <el-scrollbar style="height: 70vh">
                            <div
                                    v-for="(item, index) in imageObjs"
                                    style="padding: 8px; display: flex; justify-content: center; position: relative;cursor: pointer"
                                    :key="item"
                                    :style="
                  index === currentImageIndex
                    ? { backgroundColor: '#25CCF7' }
                    : { backgroundColor: '#fff' }
                "
                                    @click="currentImageIndex = index"

                            >
                                <img :src="item.url" alt="" style="width: 100%; border-radius: 1rem"/>
                                <img
                                        v-show="item?.isMark"
                                        src="../../assets/mark.png"
                                        alt=""
                                        style="
                    position: absolute;
                    width: 25%;
                    right: 0;
                    bottom: 0;
                    transform: translate(-20%, -20%);
                  "
                                />
                            </div>
                        </el-scrollbar>
                    </div>
                </a-col>
                <a-col :span="10">
                    <el-container>
                        <el-header>
                            <el-row class="image-navigation flex">
                                <el-col :span="8">
                                    <el-button @click="prevImage">上一张</el-button>
                                </el-col>
                                <el-col :span="8">
                                    <div class="image-count">
                                        共 {{ imageObjs?.length }} 张，这是第 {{ currentImageIndex + 1 }} 张
                                    </div>
                                </el-col>
                                <el-col :span="8">
                                    <el-button @click="nextImage">下一张</el-button>
                                </el-col>
                            </el-row>
                        </el-header>
                        <el-main style="position: relative; padding: 0">
                            <div style="height: 35rem; width: 100%; position: relative">
                                <el-image
                                        :src="currentImageObj?.url"
                                        alt="请先选择患者文件夹"
                                        style="height: 100%; border-radius: 1rem"
                                        v-loading="imageLoading"
                                >
                                    <template #error>
                                        <div style="font-size: 20rem">
                                            <el-icon>
                                                <Picture/>
                                            </el-icon>
                                        </div>
                                    </template>
                                </el-image>
                                <img
                                        v-show="currentImageObj?.isMark"
                                        style="
                    position: absolute;
                    width: 4rem;
                    height: auto;
                    top: 10%;
                    left: 24%;
                    transform: translate(-50%, -50%);
                  "
                                        src="../../assets/mark.png"
                                        alt=""
                                />
                            </div>
                            <div style="height: 10%; margin-top: 0.5rem">
                                <a-card style="padding: 10px" :body-style="{ padding: '0 10px' }">
                                    <el-descriptions title="检查过程" style="margin-top: 10px">
                                        <el-descriptions-item>
                                            {{ currentPatient?.checkingProcess }}
                                        </el-descriptions-item>
                                    </el-descriptions>
                                </a-card>
                                <a-card style="padding: 10px" :body-style="{ padding: '0 10px' }">
                                    <el-descriptions title="检查诊断" style="margin-top: 10px">
                                        <el-descriptions-item> {{ currentPatient?.diagnosis }}</el-descriptions-item>
                                    </el-descriptions>
                                </a-card>
                            </div>
                        </el-main>
                    </el-container>
                </a-col>
                <a-col :span="10">
                    <AnnotationView
                            :isLastImage="isLastImage"
                            :value-options="valueOptions"
                            :d-result="diagnosisResult"
                            @submit-annotation="submitAnnotation"
                            @formChange="handleAnnotationFormChange"
                            @submit-patient="submitPatient"
                            ref="annotationFormRef"
                    >
                    </AnnotationView>
                </a-col>
            </a-row>
        </el-main>
    </el-container>
</template>

<script setup>
import {postAction} from '@/request/request'
import {userUrl} from '@/api/api'
import {ElMessage} from 'element-plus'
import {useUserStore} from '@/store/user'
import AnnotationView from '@/components/user/AnnotationView.vue'
import {computed, reactive, ref, toRaw, watch} from "vue";

const prevPatient = () => {
    if (currentPatientIndex.value > 0) {
        currentPatientIndex.value--
        getPatientInfo(currentPatient.value.name)
    }

}

const nextPatient = () => {
    if (currentPatientIndex.value < patientsDir.value.length - 1) {
        currentPatientIndex.value++
        getPatientInfo(currentPatient.value.name)
    }

}

const patientsDir = ref([
    {name: "", checkingProcess: "", diagnosis: ""}
])

const currentPatientIndex = ref(0)

const currentPatient = computed(() => {
    return patientsDir.value[currentPatientIndex.value]
})


// 打开选择文件夹对话框
const selectDirectoryDialog = reactive({
    visible: false,
    fileList: [],
    loading: false,
    close() {
        this.visible = false
    }
})
const {user} = useUserStore()

// 选择文件夹
const selectDirectory = () => {
    selectDirectoryDialog.visible = true
    getUserFileList()
}

const getUserFileList = async () => {
    selectDirectoryDialog.loading = true
    postAction(userUrl.getFileList, {
        username: user.username
    }).then(res => {
        console.log(res)
        selectDirectoryDialog.fileList = res.data
        selectDirectoryDialog.loading = false
    }).catch(error => {
        console.error(error)
    }).finally(() => {
        selectDirectoryDialog.loading = false
    })
}
let selectedFolder = ""
const handleDirectoryClick = (row) => {
    console.log("selected folder", toRaw(row))
    if (row.type === 'directory') {
        selectedFolder = row.name
    }
}

const getPatientInfoList = (folderName) => {
    return postAction(userUrl.getPatientInfoList, {
        path: user.username + ',' + folderName
    })
}

const handleDirectoryConfirm = () => {
    if (selectedFolder) {
        // 处理选中的文件夹
        console.log('Selected folder:', selectedFolder)
        imageLoading.value = true
        getPatientInfoList(selectedFolder).then(res => {
            console.log(res)
            patientsDir.value = res.data
        }).catch(error => {
            console.error(error)
        }).finally(() => {
            imageLoading.value = false
            selectDirectoryDialog.visible = false
        })
    } else {
        ElMessage.warning('请选择一个文件夹')
    }
}
const diagnosisResult = ref([''])
const getPatientInfo = (patientName) => {
    postAction(userUrl.getPatientInfo, {
        path: user.username + ',' + selectedFolder,
        patientName: patientName
    }).then(res => {
        console.log(res)
        diagnosisResult.value = res.data.diagnosisResult
        imageObjs.value = res.data['imageList']
    })
}
watch(patientsDir, (newValue, oldValue) => {
    getPatientInfo(currentPatient.value.name)
})


const imageObjs = ref([
    {name: '', url: ''}
])
const currentImageIndex = ref(0)

const prevImage = () => {
    if (currentImageIndex.value > 0) {
        currentImageIndex.value--
    }
}
const nextImage = () => {
    if (currentImageIndex.value < imageObjs.value.length - 1) {
        currentImageIndex.value++
    }
}
const currentImageObj = computed(() => {
    return imageObjs.value[currentImageIndex.value]
})
const valueOptions = ref([''])

watch(currentImageObj, (newValue, oldValue) => {
    getImageFeature(currentImageObj.value.name)
})
const getImageFeature = (imageName) => {
    imageLoading.value = true
    postAction(userUrl.getImageFeature, {
        path: user.username + ',' + selectedFolder,
        patientName: currentPatient.value.name,
        imageName: imageName
    }).then(res => {
        console.log(res)
        if (res.code !== 200) {
            ElMessage.error(res.message)
        } else {
            valueOptions.value = res.data
        }
    }).finally(() => {
        imageLoading.value = false
    })
}

const isLastImage = computed(() => {
    return imageObjs.value.filter(item => item.isMark).length >= imageObjs.value.length-1
})

const imageLoading = ref(false)

const submitAnnotation = (valueOptions) => {
    console.log(valueOptions)
    postAction(userUrl.saveAnnotation, {
        path: user.username + ',' + selectedFolder+','+currentPatient.value.name,
        imageName: currentImageObj.value.name,
        fields: valueOptions
    }).then(res => {
        if (res.code !== 200) {
            ElMessage.error(res.message)
        }else{
            ElMessage.success(res.message)
            nextImage()
            getPatientInfo(currentPatient.value.name)
        }
    }).catch(error => {
        console.error(error)
    })
}

const handleAnnotationFormChange = (data) => {
    console.log(data)
}

const submitPatient = async (result) => {
    postAction(userUrl.savePatient, {
        path: user.username + ',' + selectedFolder+','+currentPatient.value.name,
        patientName: currentPatient.value.name,
        diagnosisResult: result,
    }).then(res => {
        console.log(res)
        if (res.code!== 200) {
            ElMessage.error(res.message)
        }else{
            ElMessage.success(res.message)
            getPatientInfo(currentPatient.value.name)

        }
    }).catch(error => {
        console.error(error)
        ElMessage.error(error.message)
    })
}


</script>

<style scoped>
.annotation-container {
    display: flex;
    flex-direction: column;
    align-items: center;
}

.flex {
    display: flex;
}

.image-preview {
    display: flex;
    gap: 10px;
    text-align: center;
    align-items: center;
    justify-content: center;
}
</style>
